package com.nutstudy.mybatis.org.mybatis.spring;

import com.nutstudy.mybatis.test.OrderMapper;
import com.nutstudy.mybatis.test.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: HyoJoo-W
 * @date: 2021-08-28 13:39
 * @description:
 */


public class NutImportBeanDefinitionRegister implements ImportBeanDefinitionRegistrar
{
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator)
    {
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(NutMapperScan.class.getName());
        String path = (String) annotationAttributes.get("value");

        NutMapperScanner scanner = new NutMapperScanner(registry);
        scanner.addIncludeFilter(new TypeFilter()
        {
            @Override
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException
            {
                return true;
            }
        });

        int scan = scanner.scan(path);
        System.out.println(scan);

//        List<Class> mapperList = new ArrayList<>();
//        mapperList.add(UserMapper.class);
//        mapperList.add(OrderMapper.class);
//
//        for (Class mapper : mapperList)
//        {
//            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//
//            beanDefinition.setBeanClass(NutFactoryBean.class);
//            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(mapper);
//
//            registry.registerBeanDefinition(mapper.getName(),beanDefinition);
//        }
    }
}
